package com.it.mybatis.common;


import com.it.mybatis.bean.User;
import com.it.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisHelloWorld {


    public static void main(String[] args) {
        String resource = "mybatis.xml";
        InputStream stream;
        try {

            /**
             * 两种方式获取配置文件
             */
            // 方法一 (注 用 MybatisHelloWorld 和 SqlSessionFactoryBuilder 都可以，不知道这是什么原理，用Object 就不可以了)
            //stream = MybatisHelloWorld.class.getClassLoader().getResourceAsStream("mybatis.xml");
            //stream = SqlSessionFactoryBuilder.class.getClassLoader().getResourceAsStream("mybatis.xml");
            //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);

            //方法二
            stream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);

            SqlSession session = sqlSessionFactory.openSession();
            UserMapper u = session.getMapper(UserMapper.class);
            System.out.println("u--->" + u.toString());
            System.err.println(u.getUser(4));
            try {
                User user = (User) session.selectOne("com.it.mapper.UserMapper.getUser", 4);
                System.out.println(user.getId() + "," + user.getUsername());
                List<User> userList = session.selectList("com.it.mapper.UserMapper.getUserByName","王麻子");
                System.out.println("getUserByName ----> " + userList);
                    /*System.out.println("-----------------------start insert------------------------------");
                    User user1 = new User();
                    user1.setName("王麻子11");
                    Integer id = session.insert("com.it.mapper.UserMapper.inserUser",user1);
                    session.commit();
                    System.out.println("id------>" + user1.getId());
                    System.out.println("-----------------------end insert------------------------------");*/
            } finally {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
